package com.yylending.las.lending;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.Loader;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.*;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.Constants;
import com.yylending.las.R;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.common.widgets.RedDotView;
import com.yylending.las.common.widgets.TelephoneTextView;
import com.yylending.las.lending.outlet.OutletActivity;
import com.yylending.las.lending.process.confirmloan.ConfirmLoanModel;
import com.yylending.las.lending.process.confirmloan.ConfirmLoanPresenter;
import com.yylending.las.lending.quota.idcard.IdCardModel;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.main.MainController;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 借钱页面-提额申请成功
 * Created by laixj on 2017/5/22.
 * Copyright ©2017 www.yylending.com. All Rights Reserved.
 */

public class IncreaseSuccessFragment extends BaseFragment implements View.OnClickListener, ConfirmLoanPresenter.View, LocationPresenter.View {

	static final String TAG = IncreaseSuccessFragment.class.getSimpleName();

	static final int LOADER_ID_CONFIRM_LOAN = 1;
	static final int LOADER_ID_LOCATE = 2;

	Unbinder unbinder;
	@BindView(R.id.title_left_iv)
	ImageView mTitleLeftIv;
	@BindView(R.id.title_tv)
	TextView mTitleTv;
	@BindView(R.id.title_right_tv)
	TextView mTitleRightTv;
	@BindView(R.id.title_right_iv)
	ImageView mTitleRightIv;
	@BindView(R.id.layout_title_bar)
	RelativeLayout mLayoutTitleBar;
	@BindView(R.id.lending_notice_tv)
	TextView mLendingNoticeTv;
	@BindView(R.id.service_phone_tv)
	TelephoneTextView mServicePhoneTv;
	@BindView(R.id.red_dot_view)
	RedDotView mRedDotView;
	@BindView(R.id.other_data)
	TextView mOtherDataTv;
	@BindView(R.id.outlet_appoint_btn)
	Button mOutletAppointBtn;

	private ConfirmLoanPresenter mConfirmLoanPresenter;
	private LocationPresenter mLocationPresenter;

	/**
	 * 额度状态
	 */
	private MyQuotaModel.ApplyStatus mApplyStatus;
	/**
	 * 定位信息
	 */
	private Location mLocation;
	/**
	 * 是否需要在定位成功之后自动预约门店
	 */
	private boolean mAutoCommit;

	private QualificationHintDialog mHintDialog;

	public static BaseFragment newInstance() {
		BaseFragment fragment = new IncreaseSuccessFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID_CONFIRM_LOAN, null, this);
		getLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
	}

	@Override
	public void onDetach() {
		dismissLoading();
		getLoaderManager().destroyLoader(LOADER_ID_CONFIRM_LOAN);
		getLoaderManager().destroyLoader(LOADER_ID_LOCATE);
		super.onDetach();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.view_stub_increase_limit_sucess, container, false);
		unbinder = ButterKnife.bind(this, rootView);
		initView();
		return rootView;
	}

	private void initView() {
		mTitleLeftIv.setImageResource(R.drawable.ic_home_help);
		mTitleTv.setText(R.string.tab_lend);
		mTitleRightIv.setImageResource(R.drawable.ic_message_white);
		mServicePhoneTv.setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);

		String text = mOtherDataTv.getText().toString();
		int startIndex = 2;
		int endIndex = startIndex + 4;
		SpannableStringBuilder builder = new SpannableStringBuilder(text);
		ForegroundColorSpan redSpan = new ForegroundColorSpan(getContext().getResources().getColor(R.color.color_4b7cf9));
		builder.setSpan(redSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		mOtherDataTv.setHighlightColor(getResources().getColor(android.R.color.transparent));
		builder.setSpan(new Clickable(this), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		mOtherDataTv.setText(builder);
		mOtherDataTv.setMovementMethod(LinkMovementMethod.getInstance());

		MainController.initRedDot(mRedDotView);
	}

	public void showHintDialog(){
		if (mHintDialog == null) {
			mHintDialog = new QualificationHintDialog(getActivity());
		}
		mHintDialog.show();
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_CONFIRM_LOAN:
				mConfirmLoanPresenter = (ConfirmLoanPresenter) data;
				mConfirmLoanPresenter.attach(this);
				break;
			case LOADER_ID_LOCATE:
				mLocationPresenter = (LocationPresenter) data;
				mLocationPresenter.attach(this);
				PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				break;
			default:
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_CONFIRM_LOAN:
				return new PresenterLoader<>(getActivity(), new ConfirmLoanPresenter.Generator());
			case LOADER_ID_LOCATE:
				return new PresenterLoader<>(getActivity(), new LocationPresenter.Generator());
			default:
				return null;
		}
	}

	@OnClick({R.id.lending_notice_tv, R.id.title_left_iv, R.id.title_right_iv, R.id.outlet_appoint_btn})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.title_left_iv:
				EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_HELP_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
			case R.id.title_right_iv:
				EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_MESSAGE_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
				MainController.hideRedDot(mRedDotView);
				break;
			case R.id.lending_notice_tv:
				EventAgent.post(new QuotaEvent.ShowLoanNoticeEvent(QuotaEvent.ShowLoanNoticeEvent.QUOTA_SHOW_LOAN_NOTICE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
			case R.id.outlet_appoint_btn:
				appointOutlet();
				break;
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		unbinder.unbind();
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onRedDotShowEvent(QuotaEvent.ShowRedDotEvent event) {
		mRedDotView.setVisibility(View.VISIBLE);
	}

	private class Clickable extends ClickableSpan {
		private final View.OnClickListener mListener;

		public Clickable(View.OnClickListener l) {
			mListener = l;
		}

		/**
		 * 重写父类点击事件
		 */
		@Override
		public void onClick(View v) {
			mListener.onClick(v);
		}

		/**
		 * 重写父类updateDrawState方法  我们可以给TextView设置字体颜色,背景颜色等等...
		 */
		@Override
		public void updateDrawState(TextPaint ds) {

		}
	}

	@Override
	public void onClick(View v) {
		// TODO: 2018/1/9 显示弹框
		showHintDialog();
	}

	@Override
	public void onFunctionalCompleted(boolean autoTips) {
		super.onFunctionalCompleted(autoTips);
		dismissLoading();
	}

	@Override
	public void confirmLoanSuccess(ConfirmLoanModel.ConfirmLoan confirmLoan) {
		mOutletAppointBtn.setEnabled(true);
		OutletActivity.start(getActivity());
	}

	@Override
	public void confirmLoanFailure(String tips) {
		showToast(tips);
		mOutletAppointBtn.setEnabled(true);
	}

	@Override
	public void confirmLoanRepeat(String tips) {
		showToast(tips);
		EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.Event.QUOTA_REFRESH, null));
	}

	@Override
	public void creditReportingOutdated() {
		showToast(R.string.credit_report_outdated);
		// 征信过期 重新获取额度状态
		EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.Event.QUOTA_REFRESH, null));
	}

	@Override
	public void getIdCardSuccess(IdCardModel.IdCard idCard) {

	}

	@Override
	public void getIdCardFailure(String s) {

	}

	/**
	 * 预约门店
	 */
	private void appointOutlet() {
		mOutletAppointBtn.setEnabled(false);
		if (null == mLocation) {
			mAutoCommit = true;
			PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
		} else {
			mAutoCommit = false;
			showLoading(false);
			confirmLoan();
		}
	}

	/**
	 * 线下借款提交
	 */
	private void confirmLoan() {
		mConfirmLoanPresenter.confirmLoan("36", "0", String.valueOf(mLocation.longitude), String.valueOf(mLocation.latitude), Constants.LOAN_OUTLET);
	}

	@Override
	public void onLocateSuccess(Location location) {
		mLocation = location;
		if (mAutoCommit)
			confirmLoan();
	}

	@Override
	public void onLocateFail(boolean noPermission) {
		if (mAutoCommit) {
			dismissLoading();
			mAutoCommit = false;
			showToast(R.string.locate_need_retry);
			mOutletAppointBtn.setEnabled(true);
		}
	}

	@Override
	public void showDialog() {

	}

	@Override
	public void dismissDialog() {

	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.ACCESS_COARSE_LOCATION:
					if (permission.granted) {
						if (mAutoCommit) {
							showLoading(false);
						}
						mLocationPresenter.startLocation(false);
					} else {
						if (mAutoCommit) {
							dismissLoading();
						}
						showNeedPermission(getString(R.string.location_right_hint, getString(R.string.app_name)));
					}
					break;
				default:
					break;
			}

		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private void showNeedPermission(String msg) {
		showOneBtnDialog(msg, getString(R.string.got_it));
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		switch (functionalCode) {
			case ConfirmLoanModel.METHOD_CONFIRM_LOAN:
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						showToast(R.string.network_need_retry);
						mOutletAppointBtn.setEnabled(true);
					}
				});
				break;
		}
	}

	/**
	 * 前往门店申请需要的资质提醒
	 * Created by laixj on 2018/1/9.
	 * Copyright ©2016 www.yylending.com. All Rights Reserved.
	 */
	public class QualificationHintDialog extends Dialog {

		@BindView(R.id.close_dialog_iv)
		ImageView mCloseDialogIv;

		public QualificationHintDialog(@NonNull Context context) {
			super(context, R.style.loading_progress_dialog);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			LayoutInflater inflater = LayoutInflater.from(getContext());
			View view = inflater.inflate(R.layout.dialog_qualification_hint, null);
			view.findViewById(R.id.close_dialog_iv).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dismiss();
				}
			});
			setContentView(view);
		}

		@Override
		public void show() {
			Window dialogWindow = getWindow();
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);
			//lp.x = 100; // 新位置X坐标
			//按比例设置距离顶部的高度
			int y = (int)(224 / 1280.0f * getResources().getDisplayMetrics().heightPixels);
			CLog.i(TAG, "y="+y);
			lp.y = y;//新位置Y坐标
			dialogWindow.setAttributes(lp);
			super.show();
		}
	}
}